#!/bin/bash

# Python自动化测试框架开发环境启动脚本
# 包含: Python应用 + Jenkins + MySQL + Redis + Nginx + Allure

set -e

echo "🚀 启动Python自动化测试框架开发环境..."

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker未运行，请先启动Docker Desktop"
    exit 1
fi

# 检查docker-compose.yml文件
if [ ! -f "docker-compose.custom.yml" ]; then
    echo "❌ 未找到docker-compose.custom.yml文件"
    exit 1
fi

# 检查自定义镜像是否存在
if ! docker images | grep -q "my-dev-env"; then
    echo "⚠️  自定义镜像my-dev-env:latest不存在"
    echo "🔨 正在构建自定义镜像..."
    if docker build -t my-dev-env:latest .; then
        echo "✅ 自定义镜像构建成功"
    else
        echo "❌ 自定义镜像构建失败，请检查网络连接"
        exit 1
    fi
else
    echo "✅ 自定义镜像my-dev-env:latest已存在"
fi

# 创建必要的目录结构
echo "📁 创建必要的目录结构..."
mkdir -p jenkins/init-scripts
mkdir -p nginx/conf.d
mkdir -p mysql/init
mkdir -p mysql/conf

# 创建默认的Redis配置文件（如果不存在）
if [ ! -f "redis/redis.conf" ]; then
    mkdir -p redis
    cat > redis/redis.conf << 'EOF'
# Redis默认配置
bind 0.0.0.0
port 6379
timeout 0
tcp-keepalive 300
daemonize no
supervised no
pidfile /var/run/redis_6379.pid
loglevel notice
logfile ""
databases 16
save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir /data
slaveof-serve-stale-data yes
slave-serve-stale-data yes
slave-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
slave-priority 100
maxmemory-policy noeviction
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-size -2
list-compress-depth 0
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
aof-rewrite-incremental-fsync yes
EOF
    echo "✅ 创建默认Redis配置文件"
fi

# 创建默认的Nginx配置（如果不存在）
if [ ! -f "nginx/conf.d/default.conf" ]; then
    cat > nginx/conf.d/default.conf << 'EOF'
server {
    listen 80;
    server_name localhost;

    location / {
        root /usr/share/nginx/html/reports;
        index index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    location /allure/ {
        alias /usr/share/nginx/html/reports/allure/;
        try_files $uri $uri/ /index.html;
    }

    # 启用目录列表
    autoindex on;
    autoindex_exact_size off;
    autoindex_localtime on;

    # 设置正确的文件类型
    location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}
EOF
    echo "✅ 创建默认Nginx配置文件"
fi

# 启动服务
echo "🔧 启动Docker Compose服务..."
docker-compose -f docker-compose.custom.yml up -d

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 10

# 检查服务状态
echo "📊 检查服务状态..."
docker-compose -f docker-compose.custom.yml ps

echo ""
echo "🎉 开发环境启动完成！"
echo ""
echo "📋 服务访问地址："
echo "   🌐 应用服务:      http://localhost:5000"
echo "   🔧 Jenkins:       http://localhost:8080"
echo "   📊 Nginx报告:    http://localhost:8081"
echo "   📈 Allure报告:   http://localhost:5050"
echo "   🗄️  MySQL:        localhost:3306 (用户: testuser, 密码: testpass)"
echo "   ⚡ Redis:         localhost:6379"
echo ""
echo "📝 常用命令："
echo "   查看日志:      docker-compose -f docker-compose.custom.yml logs -f [服务名]"
echo "   停止服务:      docker-compose -f docker-compose.custom.yml down"
echo "   重启服务:      docker-compose -f docker-compose.custom.yml restart [服务名]"
echo "   进入容器:      docker-compose -f docker-compose.custom.yml exec [服务名] bash"
echo ""
echo "🔒 数据库连接信息："
echo "   主机: localhost"
echo "   端口: 3306"
echo "   数据库: testdb"
echo "   用户: testuser"
echo "   密码: testpass"
echo ""